package org.douxiaoban.client.tab;

import java.util.ArrayList;

import org.douxiaoban.client.R;
import org.douxiaoban.client.adapter.DouGroupAdapter;
import org.douxiaoban.client.api.DouGroupApi;
import org.douxiaoban.client.widget.BaseTabView;
import org.douxiaoban.client.widget.ElasticListView;
import org.douxiaoban.client.widget.ElasticListView.OnRefreshListener;
import org.douxiaoban.data.DouGroupTopicData;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.Toast;

/**
 * 豆瓣小组,我的话题,
 * 包括我发表的和我回复的-
 * @author 6a209
 * 8:38:00 PM May 30, 2012
 */
public class DouTopicListTab extends BaseTabView{
	
	private ElasticListView mListTopic;
	private DouGroupAdapter mAdapter;
	private String mUrl;
	private DouGroupApi mDouGroupApi;
	private int mStart = 0;
	
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			hideProgress();
			ArrayList<DouGroupTopicData> list = (ArrayList<DouGroupTopicData>)msg.obj;
			if(null == list){
				Toast.makeText(getContext(), 
					getResources().getString(R.string.load_fail), Toast.LENGTH_LONG).show();
			}else{
				if(0 == mStart){
					//初始化
					mAdapter = new DouGroupAdapter(getContext(), list);
					mListTopic.setAdapter(mAdapter);
					mListTopic.onRefreshComplete();
				}else{
					//加载更多-
					mAdapter.addDataTail(list);
				}
				mStart  += list.size();
			}
		}
	};
	
	
	public DouTopicListTab(Context context){
		this(context, null);
	}
	
	public DouTopicListTab(Context context, AttributeSet attrs) {
		super(context, attrs);
		mDouGroupApi = DouGroupApi.instance(context.getApplicationContext());
		mListTopic = new ElasticListView(context);
		addToBodyView(mListTopic);
		mListTopic.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				mStart = 0;
				reqData();
			}
		});
	}
	
	public void setGetUrl(String url){
		mUrl = url;
	}
	
	public void reqData(){
		showProgress();
		new Thread(){
			@Override
			public void run(){
				ArrayList<DouGroupTopicData> list = mDouGroupApi.getDouGroupTopicData(mUrl, mStart);
				Message msg = mHandler.obtainMessage();
				msg.obj = list;
				mHandler.sendMessage(msg);
			}
		}.start();
	}
	
}